<?php
namespace app\sso\library;

use app\sso\model\Admin;
use app\sso\model\Broker;
use think\exception\HttpResponseException;
use think\Request;
use think\Response;
use think\response\Json;

/**
 * Example SSO server.
 *
 * Normally you'd fetch the broker info and user info from a database, rather then declaring them in the code.
 */
class SSOServer extends \Jasny\SSO\Server
{
    protected function createCacheAdapter()
    {
        return \think\Cache::connect(config('cache.default'));
    }

    protected function getBrokerInfo($brokerId)
    {
        $broker = Broker::get($brokerId);
        if ($broker) {
            return ['secret' => $broker['secret']];
        }
        return null;
    }

    protected function authenticate($username, $password)
    {
        if (!isset($username)) {
            return \Jasny\ValidationResult::error("username isn't set");
        }
        if (!isset($password)) {
            return \Jasny\ValidationResult::error("password isn't set");
        }
        $admin = Admin::get(['username' => $username]);
        if (!$admin) {
            return \Jasny\ValidationResult::error("Username is incorrect");
        }
        if ($admin['status'] == 'hidden') {
            return \Jasny\ValidationResult::error("Admin is forbidden");
        }

        if ($admin->password != md5(md5($password) . $admin->salt)) {
            $admin->loginfailure++;
            $admin->save();
            return \Jasny\ValidationResult::error("Password is incorrect");
        }
        $admin->loginfailure = 0;
        $admin->logintime = time();
        $admin->token = Random::uuid();
        $admin->save();

        return \Jasny\ValidationResult::success();
    }

    protected function getUserInfo($username)
    {
        $admin = Admin::where('username', $username)->field('id,username,school_id')->find();
        return ['id' => $admin->id, 'username' => $admin->username, 'school_id' => $admin->school_id];
    }

    public function userInfo()
    {
        $this->startBrokerSession();
        $user = null;

        $username = $this->getSessionData('sso_user');

        if ($username) {
            $user = $this->getUserInfo($username);
            if (!$user) return $this->fail("User not found", 500); // Shouldn't happen
        }

        $response = Response::create($user, 'json');
        throw new HttpResponseException($response);
    }
}
